package com.framework.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.ter.IntegralAgentSnDao;
import com.framework.entity.ter.IntegralAgentSn;
import com.framework.entity.ter.TerTerminalInfo;
import com.framework.service.IntegralAgentSnService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wq
 * @date 2019/10/21 11:57
 * @description
 */
@Service
public class IntegralAgentSnServiceImpl extends ServiceImpl<IntegralAgentSnDao, IntegralAgentSn> implements IntegralAgentSnService {
    @Override
    public void addRecord(Long agentId, List<TerTerminalInfo> integralTerminalList) {
        if(integralTerminalList!=null && integralTerminalList.size()>0){
            IntegralAgentSn integralAgentSn = findOneByAgentId(agentId);
            boolean condition=integralAgentSn==null;
            if(condition){
                integralAgentSn=new IntegralAgentSn();
            }

            List<String> strings = integralTerminalList.stream().map(TerTerminalInfo::getSn).collect(Collectors.toList());
            StringBuilder sb=new StringBuilder(integralAgentSn.getIntegralSnString()==null?"":integralAgentSn.getIntegralSnString());

            for (String string : strings) {
                sb.append(sb.length()==0?string:","+string);
            }
            String snListString=sb.toString();
            integralAgentSn.setAgentId(agentId);
            integralAgentSn.setIntegralSnString(snListString);
            save(integralAgentSn,condition);

        }
    }
    @Override
    public void save(IntegralAgentSn integralAgentSn, boolean condition) {
        if (condition){
            insert(integralAgentSn);
        }else {
            updateById(integralAgentSn);
        }
    }

    @Override
    public IntegralAgentSn findOneByAgentId(Long agentId){
        IntegralAgentSn ias = selectOne(new EntityWrapper<IntegralAgentSn>().eq("agent_id", agentId));
        return ias;
    }

    @Override
    public IntegralAgentSn findBySn(String sn) {
        IntegralAgentSn integralAgentSn = selectOne(new EntityWrapper<IntegralAgentSn>().where(" FIND_IN_SET({0},integral_sn_string)", sn));
        return integralAgentSn;
    }

    @Override
    public void dropSn(IntegralAgentSn integralAgentSn, String sn) {
        String snString = integralAgentSn.getIntegralSnString();

        String [] snArray=snString.split(",");

        List<String> collect = Arrays.stream(snArray).filter(e -> !e.equals(sn)).collect(Collectors.toList());

        String join = StringUtils.join(collect, ",");

        integralAgentSn.setIntegralSnString(join);

        updateById(integralAgentSn);
    }

}
